import React, { useEffect, useState } from "react";
import axios from "axios";
import { Button, Space, Table, Tag } from "antd";
import { message, Popconfirm } from "antd";
import { Modal } from "antd";
import { Checkbox, Form, Input } from "antd";
import { addApi, addListapi } from "../../../api/user";
import { Drawer } from "antd";
import { useDispatch } from "react-redux";
import { password } from "../../start/status/status";
function Index() {
  const dispatch = useDispatch();
  const [data, setdata] = useState();
  const [title, settitle] = useState();
  const [addForm] = Form.useForm();
  const [count, setcount] = useState(0);
  const [page, setpage] = useState(1);
  const [pageSize, setpageSize] = useState(10);
  const getData = () => {
    axios
      .get("/api/article/list", {
        params: {
          page: page,
          pageSize: pageSize,
        },
      })
      .then((res) => {
        console.log(res);
        setdata(res.data.rows);
        setcount(res.data.count);
      });
  };
  useEffect(() => {
    getData();
  }, [page, pageSize]);
  //详情
  const [open, setOpen] = useState(false);
  const [qx, setqx] = useState("");
  const showDrawer = (id) => {
    setOpen(true);
    axios.get(`/api/article/${id}`, { params: { id } }).then((res) => {
      setqx(res.data);
      dispatch(password(res.data));
    });
  };
  const onClose = () => {
    setOpen(false);
  };
  //分页
  const add = (page, pageSize) => {
    setpage(page);
    setpageSize(pageSize);
  };
  //这是添加弹框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
    settitle("添加");
    addForm.resetFields("");
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onFinish = async (values) => {
    console.log("Success:", values);
    if (title === "添加") {
      const data = {
        title: values.title, //文章标题
        content: values.content, //文章内容
        tagList: ["HTTP"], //标签  array[string]
        categoryList: ["HTTP"], //分类  array[string]
        authorId: 47529555, //用户id 暂时写死47529555 登陆成功后返回的用
      };
      const res = await addListapi(data);
      console.log(res);
      alert("添加成功");
      getData();
      setIsModalOpen(false);
    } else if (title === "编辑") {
      const data1 = {
        title: values.title, //文章标题
        content: values.content, //文章内容
        tagList: ["HTTP"], //标签  array[string]
        categoryList: ["HTTP"], //分类  array[string]
        authorId: 47529555, //用户id 暂时写死47529555 登陆成功后返回的用
      };
      const res1 = await addApi(id, data1);
      console.log(res1);
      alert("编辑成功");
      getData();
      setIsModalOpen(false);
    }
  };
  //编辑
  const [id, setId] = useState("");
  const bianji = (record) => {
    setIsModalOpen(true);
    settitle("编辑");
    addForm.setFieldsValue(record);
    setId(record.id);
  };
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "作者",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "标签",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "文章标题",
      dataIndex: "viewCount",
      key: "viewCount",
    },
    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm
            title="这是删除弹框"
            description="你确定要删除吗"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>

          <Button type="primary" onClick={() => showDrawer(record.id)}>
            详情
          </Button>
          <Button onClick={() => bianji(record)}>修改</Button>
          <Button onClick={() => xiajia(record.id)}>下架</Button>
        </Space>
      ),
    },
  ];
  //下架
  const xiajia = (id) => {
    setdata(data.filter((data) => data.id !== id));
  };
  //  删除
  const confirm = (id) => {
    setdata(data.filter((data) => data.id !== id));
    message.success("删除成功");
  };
  const cancel = (e) => {
    console.log(e);
    message.error("取消删除");
  };
  return (
    <div>
      <Button type="primary" onClick={showModal}>
        添加
      </Button>
      <Modal
        title={title}
        closable={{ "aria-label": "Custom Close Button" }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={addForm}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="作者"
            name="title"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="标签"
            name="content"
            rules={[{ required: true, message: "Please input your password!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="时间" name="createdAt">
            <Input />
          </Form.Item>
          <Form.Item label="文章标题" name="viewCount">
            <Input />
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Drawer
        title="详情"
        closable={{ "aria-label": "Close Button" }}
        onClose={onClose}
        open={open}
      >
        <p>作者：{qx.title}</p>
        <p>标签：{qx.content}</p>
        <p>时间：{qx.createdAt}</p>
        <p>文章标题：{qx.viewCount}</p>
      </Drawer>
      <Table
        columns={columns}
        dataSource={data}
        pagination={{
          total: count,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: add,
        }}
      />
    </div>
  );
}

export default Index;
